import aiofiles
import base64
from pathlib import Path
from typing import Optional, Tuple
import uuid
from fastapi import UploadFile
from app.config import settings
from app.utils.logger import logger
from app.services.video_manager import VideoManager

class VideoService:
    def __init__(self):
        self.upload_dir = Path(settings.UPLOAD_DIR)
        self.max_file_size = settings.MAX_FILE_SIZE
        self.allowed_extensions = settings.ALLOWED_EXTENSIONS.split(',')
        self.video_manager = VideoManager()
    
    def validate_file(self, file: UploadFile) -> bool:
        """验证上传文件"""
        # 检查文件扩展名
        if file.filename:
            ext = Path(file.filename).suffix.lower().lstrip('.')
            if ext not in self.allowed_extensions:
                return False
        
        # 检查文件大小（这里简化处理，实际应该在上传过程中检查）
        return True
    
    async def save_upload_file(self, file: UploadFile) -> Tuple[Path, str]:
        """保存上传文件并返回文件路径和访问URL"""
        # 生成唯一文件名
        file_id = str(uuid.uuid4())
        ext = Path(file.filename).suffix if file.filename else '.mp4'
        filename = f"{file_id}{ext}"
        file_path = self.upload_dir / filename
        
        # 保存文件
        async with aiofiles.open(file_path, 'wb') as f:
            content = await file.read()
            await f.write(content)
        
        # 获取文件大小并记录到视频管理器
        file_size = file_path.stat().st_size
        self.video_manager.add_video_record(filename, file.filename or "unknown", file_size)
        
        # 生成访问URL
        video_url = f"{settings.VIDEO_BASE_URL}/videos/{filename}"
        
        logger.info(f"文件已保存: {file_path}")
        logger.info(f"视频访问URL: {video_url}")
        return file_path, video_url
    
    async def convert_video_to_base64(self, video_path: Path) -> str:
        """将视频文件转换为base64编码"""
        try:
            logger.info(f"开始转换视频为base64: {video_path}")
            
            # 读取视频文件
            async with aiofiles.open(video_path, 'rb') as f:
                video_content = await f.read()
            
            # 转换为base64
            video_b64 = base64.b64encode(video_content).decode('utf-8')
            
            logger.info(f"视频转换完成，大小: {len(video_content)} bytes")
            return video_b64
            
        except Exception as e:
            logger.error(f"视频转换失败: {str(e)}")
            raise Exception(f"视频处理失败: {str(e)}")
    
    def get_video_mime_type(self, file_path: Path) -> str:
        """根据文件扩展名获取MIME类型"""
        ext = file_path.suffix.lower()
        mime_types = {
            '.mp4': 'video/mp4',
            '.avi': 'video/x-msvideo',
            '.mov': 'video/quicktime',
            '.mkv': 'video/x-matroska',
            '.webm': 'video/webm',
            '.flv': 'video/x-flv'
        }
        return mime_types.get(ext, 'video/mp4')
    
    async def cleanup_temp_files(self, file_path: Path):
        """清理临时文件"""
        try:
            # 如果配置为保留上传文件，则不删除
            if settings.KEEP_UPLOADED_FILES:
                logger.info(f"配置为保留上传文件，跳过删除: {file_path}")
                return
                
            if file_path.exists():
                file_path.unlink()
                logger.info(f"临时文件已删除: {file_path}")
        except Exception as e:
            logger.warning(f"清理临时文件失败: {str(e)}")
    
    def get_video_url(self, filename: str) -> str:
        """根据文件名生成视频访问URL"""
        return f"{settings.VIDEO_BASE_URL}/videos/{filename}"
    
    def get_filename_from_path(self, file_path: Path) -> str:
        """从文件路径获取文件名"""
        return file_path.name